/*
 * The string "PAYPALISHIRING" is written in a zigzag pattern
 * on a given number of rows like this: (you may want to display
 * this pattern in a fixed font for better legibility)

    P   A   H   N
    A P L S I I G
    Y   I   R
 * And then read line by line: "PAHNAPLSIIGYIR"
 * Write the code that will take a string and make this conversion given a number of rows:

 * string convert(string text, int nRows);
 * convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
 */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

char *convert(char *s, int numRows) {
    /**
    第一行     1          2 * (numRows - 1) - 1   2 * (numRows - 1) - 1
    第二行     2          2 * (numRows - 2) - 1   2 * (2 - 1) - 1
    第n 行     n          2 * (numRows - n) - 1   2 * (n - 1) - 1
    末  行     numRows    2 * (numRows - 1) - 1   2 * (numRows - 1) - 1
    */
    int len, i, j, n, flag;
    char *str = NULL;

    len = strlen(s);
    str = (char *) malloc(sizeof(char) * len + 1);
    i = 0;
    n = 0;
    if (numRows == 1) {
        for (j = 0; j < len; j++) {
            str[j] = s[j];
        }
        str[j] = '\0';
        return str;
    }

    do {
        str[n++] = s[i];
        i += 2 * (numRows - 1);
    } while (i < len);

    if (n < len) {
        for (j = 2; j < numRows; j++) {
            i = j - 1;
            flag = 0;
            do {
                str[n++] = s[i];
                if (flag) {
                    i += 2 * (j - 1);
                    flag--;
                } else {
                    i += 2 * (numRows - j);
                    flag++;
                }
            } while (i < len);
        }
    }

    if (n < len) {
        i = numRows - 1;
        do {
            str[n++] = s[i];
            i += 2 * (numRows - 1);
        } while (i < len);
    }

    str[n] = '\0';
    return str;
}

int main()
{
    char * s;
    char * param = "wlrbbmqbhcdarzowkkyhiddqscdxrjmowfrxsjybldbefsarcbynecdyggxxpklorellnmpapqfwkhopkmco";
    s = convert(param, 61);
    printf("%s\n", s);
    return 0;
}
